import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);//vue的插件机制

//Vuex.Store 构造器选项
const store = new Vuex.Store({
	state:{//存放状态
		"addressList": uni.getStorageSync('addressList') || []
	},
	getters: {
		isCheckAll(state) {
			return state.addressList.every(item => item.checked)
		},
		isDisable(state) {
			return state.addressList.every(item => !item.checked)
		}
	},
	mutations: {
		addAdress(state, payload) {
			// 添加地址，id为时间戳
			state.addressList.unshift({
				...payload,
				id: new Date().getTime()
			})
			uni.setStorageSync('addressList', state.addressList)
		},
		deleteAddress(state, payload) {
			// 删除地址，传入要删除的id
			const {id} = payload;
			state.addressList = state.addressList.filter(item => item.id !== id)
			uni.setStorageSync('addressList', state.addressList)
		},
		editAddress(state, payload) {
			// 编辑id匹配到，进行payload数据覆盖，没匹配到的，isDefault需保持最多为1个
			state.addressList = state.addressList.map(item => {
				if(item.id == payload.id) {
					return payload
				}
				return {
					...item,
					isDefault: payload.isDefault ? false : item.isDefault
				}
			})
			uni.setStorageSync('addressList', state.addressList)
		},
		checkItem(state, payload) {
			const {id, checked} = payload;
			state.addressList = state.addressList.map(item => {
				if(item.id === id) {
					return {
						...item,
						checked,
					}
				}
				return item
			})
			uni.setStorageSync('addressList', state.addressList)
		},
		checkAll(state, payload) {
			state.addressList = state.addressList.map(item => {
				return {
					...item,
					checked: payload.checked
				}
			})
			uni.setStorageSync('addressList', state.addressList)
		},
		deleteSelect(state) {
			state.addressList = state.addressList.filter(item => !item.checked)
			uni.setStorageSync('addressList', state.addressList)
		}
	}
})
export default store